import { Radio, RadioProps, Select, SelectProps } from "antd";
import { FC, useEffect, useState } from "react";
import { getDictionaryData } from "@/utils";
import { DefaultOptionType } from "antd/es/select";

export type DictionaryFormItemProps = SelectProps &
    RadioProps & {
        dictType: string;
        dictClass: "number" | "boolean" | "string";
        componentType: "select" | "radio";
        value?: OptionType["value"];
        onChange?: (value: OptionType["value"]) => void;
    };
interface OptionType {
    value: number | boolean | string;
    label: string;
}
const DictionaryFormItem: FC<DictionaryFormItemProps> = ({ dictType, dictClass, componentType, value, onChange, ...remainingProps }) => {
    const [data, setData] = useState<OptionType[]>([]);

    useEffect(() => {
        getDictionaryData(dictType).then(res => {
            let list: OptionType[] = res;
            if (dictClass === "number") list = res.map(item => ({ value: +item.value, label: item.label }));
            if (dictClass === "boolean") list = res.map(item => ({ value: item.value === "true" ? true : false, label: item.label }));
            setData(list);
        });
    }, []);

    const [innerValue, setInnerValue] = useState<OptionType["value"] | undefined>(undefined);
    useEffect(() => {
        setInnerValue(value);
    }, [value]);

    const handleChange = (val: OptionType["value"]) => {
        setInnerValue(val);
        onChange?.(val);
    };
    return (
        <>
            {componentType === "select" && <Select {...remainingProps} value={innerValue} onChange={handleChange} options={data as DefaultOptionType[]} />}
            {componentType === "radio" && (
                <Radio.Group {...remainingProps as RadioProps} value={innerValue} onChange={e => handleChange(e.target.value)}>
                    {data.map((item, index) => (
                        <Radio key={index} value={item.value}>
                            {item.label}
                        </Radio>
                    ))}
                </Radio.Group>
            )}
        </>
    );
};

export default DictionaryFormItem;
